from time import sleep
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
import selenium.webdriver.support.ui as ui
from selenium.webdriver.common.by import By
import wget
import os, time
from datetime import datetime

from selenium.webdriver.support.wait import WebDriverWait


def startBrowser(driverPath, openUrl):
    browser = webdriver.Chrome(service=driverPath)

    browser.get(openUrl)
    return browser


def login(browser, account_text, passwd_text):
    """
    :param browser:  驱动
    :param account:  账号
    :param passwd:  密码
    :return:
    """
    " step 1 . 填充账号"
    account = browser.find_element(By.XPATH, '//*[@id="account"]')
    account.clear()
    account.send_keys(account_text)
    " step2. 填充密码"
    passwd = browser.find_element(By.XPATH, '//*[@id="loginPanel"]/div/div[2]/form/table/tbody/tr[2]/td/input')
    passwd.clear()
    passwd.send_keys(passwd_text)
    "step3. 点击登录"
    login_btn = browser.find_element(By.XPATH, '//*[@id="submit"]')
    login_btn.click()


def fill_report(browser, expected_remaining):
    """wait_alert = ui.WebDriverWait(browser,5)
    wait_alert.until(lambda driver: browser.find_element(By.XPATH,'//*[@id="recordForm"]'))"""

    browser.switch_to.frame('iframe-triggerModal')
    menu_tables = browser.find_elements(By.CSS_SELECTOR, '#recordForm > table > tbody')
    # print(len(menu_tables))

    for tr in menu_tables:
        itr = tr.find_elements(By.CLASS_NAME, "text-center")
        print(len(itr))
        for index in range(len(itr)):
            print("====" + index.__str__() + "====")
            print(itr[index].text)
            if itr[index].text.__contains__(datetime):
                print("true")
                break
            else:
                if itr[index].text == "1":
                    print("true")
                    itr[index + 2].send_keys("8")
                    itr[index + 3].send_keys(expected_remaining)
                    text = tr.find_elements(By.ID, "work[1]")
                    print(len(text))
                    text[0].send_keys(text_conf)
                    break
    if expected_remaining == 0:
        browser.find_element(By.ID, 'submit').click()
        time.sleep(2)
        alert = browser.switch_to.alert
        print(alert.text)
        alert.accept()
    #     driver.switchTo().alert().accept() 点击取消
    else:
        submit = browser.find_element(By.ID, 'submit')
        submit.click()
    # exit()
    # else:
    # print("false")

    # itr[4].find_element(By.TAG_NAME, "textarea").send_keys("-------------------------")

    # input_area=tr.find_elements_by_class_name("text-left")
    # input_area[1].send_keys("胜多负少的")
    # idx_text =itr[0].text
    # print(idx_text)


# '''列表剩余一个任务无分支'''
def get_time(browser, idx):
    index = idx + 1
    wait = ui.WebDriverWait(browser, 5)
    wait.until(
        lambda driver: browser.find_element(By.XPATH, '//*[@id="tasktable"]/tbody/tr[' + str(index) + ']/td[10]'))
    """查看剩余时间"""
    remaining = browser.find_element(By.XPATH, '//*[@id="tasktable"]/tbody/tr[' + str(index) + ']/td[10]')
    remaining_time = remaining.text
    print("剩余时间:" + remaining_time)
    """查看初始时间"""
    initial_location = browser.find_element(By.XPATH, '//*[@id="tasktable"]/tbody/tr[' + str(index) + ']/td[8]')
    initial_time = initial_location.text
    print("初始时间:" + initial_time)
    return remaining_time, initial_time


def daily_report(browser):
    # browser.refresh()
    wait = ui.WebDriverWait(browser, 5)
    wait.until(lambda driver: browser.find_element(By.CSS_SELECTOR, '#tasktable > tbody'))
    task_tables = browser.find_elements(By.CSS_SELECTOR, '#tasktable > tbody')
    for tr in task_tables:
        itr = tr.find_elements(By.CSS_SELECTOR, 'tr')
        print(len(itr))

        if len(itr) == 1:
            for index in range(len(itr)):
                print(itr[index].text)
                if itr[index].text.__contains__("进行中"):
                    print("only开始进行中任务")
                    wait = ui.WebDriverWait(browser, 5)
                    wait.until(lambda driver: browser.find_element(By.XPATH, '//*[@id="tasktable"]/tbody/tr/td[10]'))
                    """查看剩余时间"""
                    remaining = browser.find_element(By.XPATH,
                                                     '//*[@id="tasktable"]/tbody/tr/td[10]')
                    remaining_time = remaining.text
                    print("剩余时间:" + remaining_time)
                    print("该任务已开始")
                    """点击时间记录按钮"""
                    account = browser.find_element(By.XPATH, '//*[@id="tasktable"]/tbody/tr/td[13]/a[2]')
                    account.click()
                    expected_remaining = int(remaining_time) - 8
                    print("剩余时间:" + str(expected_remaining))
                    fill_report(browser, expected_remaining)
                    browser.close()
                    break
                else:
                    print("only任务未开始选择任务")
                    wait = ui.WebDriverWait(browser, 5)
                    wait.until(lambda driver: browser.find_element(By.XPATH, '//*[@id="tasktable"]/tbody/tr/td[10]'))
                    """查看初始时间"""
                    initial_location = browser.find_element(By.XPATH,
                                                            '//*[@id="tasktable"]/tbody/tr/td[8]')
                    initial_time = initial_location.text
                    print("初始时间:" + initial_time)
                    tr_list = browser.find_element(By.CSS_SELECTOR,
                                                   '#tasktable > tbody > tr > td.c-id')
                    task_id = tr_list.text
                    print(task_id)
                    if task_id == taskId:
                        print("该任务未开始")
                        """点击时间记录按钮"""
                        account = browser.find_element(By.XPATH, '//*[@id="tasktable"]/tbody/tr/td[13]/a[3]')
                        account.click()
                        expected_remaining = int(initial_time) - 8
                        print("剩余时间:" + str(expected_remaining))
                        fill_report(browser, expected_remaining)
                        browser.close()
                        break
        else:
            # i = 1
            # while i <= len(itr):
            #     i = i+1
            for index in range(len(itr)):
                print(itr[index].text)
                if itr[index].text.__contains__("已完成"):
                    print("关闭已完成任务")
                    # tr_list = browser.find_elements(By.CSS_SELECTOR,
                    #                                 '#tasktable > tbody > tr:nth-child(' + str(index + 1) + ') > td.c-id')
                    # task_id = tr_list[0].text
                    # print(task_id)
                    browser.find_element(By.XPATH,
                                         '//*[@id="tasktable"]/tbody/tr[' + str(index + 1) + ']/td[13]/a[1]').click()
                    browser.switch_to.frame('iframe-triggerModal')
                    close_button = browser.find_element(By.ID, 'submit')
                    close_button.click()
                    # browser.switch_to.parent_frame()
                    browser.close()
                    browser1 = startBrowser(driverPath, openUrl)
                    # browser.switch_to.default_content()
                    time.sleep(1)
                    browser1.switch_to.window(browser1.window_handles[0])
                    wait = ui.WebDriverWait(browser1, 5)
                    wait.until(lambda driver: browser1.find_element(By.XPATH, '//*[@id="account"]'))
                    login(browser1, name, password)
                    daily_report(browser1)
                    break
                elif itr[index].text.__contains__("进行中"):
                    print("开始进行中任务")
                    remaining_time = get_time(browser, index)[0]
                    print("该任务已开始")
                    """点击时间记录按钮"""
                    account = browser.find_element(By.XPATH,
                                                   '//*[@id="tasktable"]/tbody/tr[' + str(index + 1) + ']/td[13]/a[2]')
                    account.click()
                    expected_remaining = int(remaining_time) - 8
                    print("剩余时间:" + str(expected_remaining))
                    fill_report(browser, expected_remaining)
                    browser.close()
                    break
                else:
                    print("任务未开始选择任务")
                    tr_list = browser.find_elements(By.CSS_SELECTOR,
                                                    '#tasktable > tbody > tr:nth-child(' + str(
                                                        index + 1) + ') > td.c-id')
                    task_id = tr_list[0].text
                    print(task_id)
                    if task_id == taskId:
                        initial_time = get_time(browser, index)[1]
                        print("该任务未开始")
                        """点击时间记录按钮"""
                        account = browser.find_element(By.XPATH, '//*[@id="tasktable"]/tbody/tr[' + str(
                            index + 1) + ']/td[13]/a[3]')
                        account.click()
                        expected_remaining = int(initial_time) - 8
                        print("剩余时间:" + str(expected_remaining))
                        fill_report(browser, expected_remaining)
                        browser.close()
                        break
    # exit()
    # """ step 1 . 打开日报"""
    # """account = browser.find_element_by_xpath('//*[@id="taskList"]/tbody/tr/td[12]/a[2]')"""
    # remaining_time = get_time(browser)[0]
    # initial_time = get_time(browser)[1]
    # if remaining_time == initial_time:
    #     print("该任务未开始")
    #     """点击时间记录按钮"""
    #     account = browser.find_element(By.XPATH, '//*[@id="tasktable"]/tbody/tr/td[13]/a[3]')
    #     account.click()
    #     expected_remaining = int(initial_time) - 8
    #     print("剩余时间:" + str(expected_remaining))
    #     fill_report(browser, expected_remaining)
    # else:
    #     print("该任务已开始")
    #     """点击时间记录按钮"""
    #     account = browser.find_element(By.XPATH, '//*[@id="tasktable"]/tbody/tr/td[13]/a[2]')
    #     account.click()
    #     expected_remaining = int(remaining_time) - 8
    #     print("剩余时间:" + str(expected_remaining))
    #     fill_report(browser, expected_remaining)


"""
    for idx  in range(1, len(menu_tables)):


        if(menu_tables[idx].find_element_by_id('id['+str(idx)+']')):
            nb=menu_tables[idx].find_element_by_id('id['+idx+']').text
            print("idx == " +idx )

        print(menu_tables[idx].text)

"""


def load():
    out_filename = 'report.txt'
    if os.path.isfile(out_filename):
        # 删除下载文件
        os.remove(out_filename)
    # 网络地址
    data_url = "https://gitee.com/dogsled/lddb_chandao/raw/master/chandao_report/report.md"
    wget.download(data_url, out=out_filename)
    file_content = open(out_filename, mode="r", encoding="utf-8").readlines()
    # for x in file_content:
    #     print(x)
    filter_content = filter(lambda x: not (x.__contains__("日期") or x.__contains__("|-")), file_content)
    cur_data_str = datetime.now().strftime("%Y-%m-%d")
    # cur_data_str = "2022-03-17"
    filter_current_content = filter(lambda x: x.__contains__(cur_data_str), filter_content)
    arr = []
    for x in filter_current_content:
        arr.append(x.split("|"))
        # print(x.split("|"))
    # print(arr)
    return arr


if __name__ == '__main__':
    driverPath = Service(r"G:/Soft/chromedriver_win32/chromedriver.exe")
    arr = load()
    # openUrl = "http://10.71.164.30:8680/zentao/user-login.html"
    openUrl = "http://10.71.164.30:8680/zentao/my-task-assignedTo-status_desc-0-20-1.html"
    for item in arr:
        datetime = item[1]
        text_conf = item[5]
        name = item[3]
        password = item[4]
        taskId = item[2]
        print(text_conf, name, password, datetime, taskId)
        dirver = startBrowser(driverPath, openUrl)
        login(dirver, name, password)
        daily_report(dirver)
        #
        # input("按任意键退出")

exit()
